package org.xp.judgeplatform.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xp.judgeplatform.common.ApiResponse;
import org.xp.judgeplatform.pojo.dto.UserDTO.UserLoginDTO;
import org.xp.judgeplatform.pojo.dto.UserDTO.UserRegisterDTO;
import org.xp.judgeplatform.pojo.dto.UserDTO.UserProfileDTO;
import org.xp.judgeplatform.pojo.dto.UserDTO.UserPasswordDTO;
import org.xp.judgeplatform.pojo.vo.UserVO.UserVO;
import org.xp.judgeplatform.security.UserPrincipal;
import org.xp.judgeplatform.service.UserService;

@RestController
@RequestMapping("/user")
@Slf4j
@AllArgsConstructor
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:3000"})
@Tag(name = "用户管理", description = "用户注册、登录、信息管理等接口")
public class UserController {

    private final UserService userService;

    @PostMapping(value = "/register", consumes = MediaType.APPLICATION_JSON_VALUE)
    @Operation(
        summary = "用户注册",
        description = "新用户注册账号，需要提供用户名、密码等基本信息"
    )
    public ApiResponse<UserVO> register(
            @Parameter(description = "用户注册信息", required = true)
            @Valid @RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("收到注册请求: {}", userRegisterDTO.getUsername());
        UserVO userVO = userService.register(userRegisterDTO);
        return ApiResponse.success(userVO);
    }

    @PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
    @Operation(
        summary = "用户登录",
        description = "用户登录系统，返回JWT令牌"
    )
    public ApiResponse<UserVO> login(
            @Parameter(description = "用户登录信息", required = true)
            @Valid @RequestBody UserLoginDTO userLoginDTO) {
        log.info("收到登录请求: {}", userLoginDTO.getUsername());
        UserVO userVO = userService.login(userLoginDTO);
        log.info("登录成功: {}, 角色: {}", userLoginDTO.getUsername(), userVO.getRole());
        return ApiResponse.success(userVO);
    }

    @PutMapping(value = "/profile/{userId}", consumes = MediaType.APPLICATION_JSON_VALUE)
    @Operation(
        summary = "更新用户信息",
        description = "更新用户的个人信息，需要登录",
        security = @SecurityRequirement(name = "bearerAuth")
    )
    public ApiResponse<UserPrincipal> updateUserInfo(
            @Parameter(description = "用户ID", required = true, example = "1")
            @PathVariable Integer userId,
            @Parameter(description = "用户更新信息", required = true)
            @Valid @RequestBody UserProfileDTO userProfileDTO, Authentication authentication) {

        // 只能修改自己的信息
        UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
        return ApiResponse.success(principal);
    }

    @PostMapping("/avatar/{userId}")
    @Operation(
        summary = "更新用户头像",
        description = "上传并更新用户头像，需要登录",
        security = @SecurityRequirement(name = "bearerAuth")
    )
    public ApiResponse<String> updateAvatar(
            @Parameter(description = "用户ID", required = true, example = "1")
            @PathVariable Integer userId,
            @Parameter(description = "头像文件", required = true)
            @RequestParam("file") MultipartFile file, 
            Authentication authentication) {

        // 验证权限：只能修改自己的头像
        UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
        if (!principal.getId().equals(userId)) {
            return ApiResponse.error("无权修改其他用户头像");
        }

        // 验证文件是否为空
        if (file == null || file.isEmpty()) {
            return ApiResponse.error("请选择要上传的文件");
        }

        try {
            String avatarUrl = userService.updateAvatar(userId, file);
            return ApiResponse.success(avatarUrl);
        } catch (Exception e) {
            log.error("上传头像失败，用户ID: {}", userId, e);
            return ApiResponse.error("上传失败: " + e.getMessage());
        }
    }

    @PutMapping(value = "/password/{userId}", consumes = MediaType.APPLICATION_JSON_VALUE)
    @Operation(
        summary = "修改用户密码",
        description = "修改用户登录密码，需要提供当前密码验证",
        security = @SecurityRequirement(name = "bearerAuth")
    )
    public ApiResponse<Void> changePassword(
            @Parameter(description = "用户ID", required = true, example = "1")
            @PathVariable Integer userId,
            @Parameter(description = "密码修改信息", required = true)
            @Valid @RequestBody UserPasswordDTO userPasswordDTO, Authentication authentication) {

        UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
        if (!principal.getId().equals(userId)) {
            return ApiResponse.error("无权修改其他用户密码");
        }
        userService.changePassword(userId, userPasswordDTO);
        return ApiResponse.success();
    }
}